#!/usr/bin/env python3
# $Id: test3-5.py 7c6bb3d1dea5 2012/08/26 01:44:08 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: 7c6bb3d1dea5 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-08-26 01:44:08Z $"

from __future__ import division

import re
import math

from pyparsing import Word, alphas, ParseException, Literal, CaselessLiteral
from pyparsing import Combine, Optional, nums, Or, Forward, ZeroOrMore
from pyparsing import StringEnd, alphanums

from venya3.lib import console

exprStack = []
varStack = []
variables = {}

operator = {
      '+' : (lambda ix, jy: ix + jy),
      '-' : (lambda ix, jy: ix - jy),
      '*' : (lambda ix, jy: ix * jy),
      '/' : (lambda ix, jy: ix / jy),
      '^' : (lambda ix, jy: ix ** jy)
      }

def pushFirst(string, location, tokens):
   exprStack.append(tokens[0])

def assignVar(string, location, tokens):
   varStack.append(tokens[0])

def grammar():
   point = Literal(".")
   exp = CaselessLiteral("E")
   plusOrMinus = Literal("+") | Literal("-")
   number = Word(nums)
   integer = Combine(Optional(plusOrMinus) + number)
   floatNumber = Combine(integer + Optional(point + Optional(number)) +
         Optional(exp + integer))
   ident = Word(alphas, alphanums + "-" + "_")
   plus = Literal("+")
   minus = Literal("-")
   mult = Literal("*")
   div = Literal("/")
   lpar = Literal("(").suppress()
   rpar = Literal(")").suppress()
   addop = plus | minus
   multop = mult | div
   expop = Literal("^")
   assign = Literal("=")

   expr = Forward()
   atom = ((exp | floatNumber | integer | ident).setParseAction(pushFirst) | (
      lpar + expr.suppress() + rpar))
   factor = Forward()
   factor << atom + ZeroOrMore((expop + factor).setParseAction(pushFirst))
   term  = factor + ZeroOrMore((multop + factor).setParseAction(pushFirst))
   expr << term + ZeroOrMore((addop + term).setParseAction(pushFirst))
   bnf = Optional((ident + assign).setParseAction(assignVar)) + expr

   return bnf + StringEnd()

def evaluate(string):
   op = string.pop()
   retval = None
   if op in "+-*/^":
      op2 = evaluate(string)
      op1 = evaluate(string)
      retval = operator[op](op1, op2)
   elif op.lower() == "pi":
      retval = math.pi
   elif op == "E":
      retval = math.e
   elif re.search("^[a-zA-Z][\w]*$", op):
      if op in variables:
         retval = variables[op]
      else:
         retval = 0
   elif re.search("^[-+]?\d+$", op):
      retval = int(op)
   else:
      retval = float(op)

   return retval

if __name__ == "__main__":
   console = console.CmdLine()
   pattern = grammar()
   flag = True
   while flag:
      line = None
      try:
         prompt = "calc [%d]> " %console.GetHistLength()
         line = console.raw_input(prompt)
      except EOFError:
         flag = False
         print
      except KeyboardInterrupt:
         print
         pass

      if line:
         res = None
         try:
            results = pattern.parseString(line.strip())
            res = evaluate(exprStack)
            variables['ans'] = res
         except ParseException as err:
            print(err)
         else:
            print(res)
            if len(varStack) == 1:
               variables[varStack.pop()] = res
